package cn.kgc.libraryapplication.controller;

import cn.kgc.libraryapplication.service.BookService;
import cn.kgc.librarycommon.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class BookController {
    
    @Autowired
    private BookService bookService;

    @RequestMapping("/books")
    public String getAllBooks(Integer pageNo, String bookName, String authorName,Model model){
        pageNo = pageNo == null?1:pageNo;
        bookName = bookName == null?"":bookName;
        authorName = authorName == null?"":authorName;
        System.out.println(authorName);
        PageResult<BookInfo> allBooks = bookService.getAllBooks(pageNo, bookName, authorName);
        List<Category> allCategory = bookService.getAllCategory();
        System.out.println(allBooks.getResultList().toString());
        model.addAttribute("allbooks" ,allBooks);
        model.addAttribute("bookName", bookName);
        model.addAttribute("authorName", authorName);
        model.addAttribute("allCategory", allCategory);
        return "book-list";
    }

    @ResponseBody
    @RequestMapping("/borrow")
    public Map<String, Object> borrow(Integer fid, HttpSession session){
        Map<String, Object> map = new HashMap<>();
        User user = (User)session.getAttribute("user");
        System.out.println(user);
        System.out.println("application层fid:"+fid);
        if(user == null){
            map.put("result", -1);
            map.put("message", "请先登录！");
            return map;
        }
        if(fid == null){
            map.put("result", -2);
            map.put("message", "请选择图书！");
            return map;
        }
        //借阅方法
        Integer result = bookService.borrow(user.getUid(), fid);
        map.put("result", 1);
        map.put("message", "借阅成功");
        return map;
    }

}
